#include "widget.h"
#include "ui_widget.h"
#include<QMessageBox>
#include<QtDebug>
#include<QIcon>
#include <QHostAddress>
#include<QJsonDocument>
#include<QJsonObject>
#include<QJsonArray>
#include<QPixmap>
#include<QVector>
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>
#include <QtCharts/QAreaSeries>
#include<QDebug>
#include "QtCharts/QChart"
#include "QLineSeries"
#include "QValueAxis"
#include "QTimer"
#include "QTime"
#include "QList"
#include "qmath.h"
#include "QPointF"
#include "QDebug"
#include "QChartView"
QT_CHARTS_USE_NAMESPACE
QChart *m_chart;
QLineSeries *m_series;
//QList<double> dataList;//存储业务数据
int maxSize = 5000;

//QTimer updateTimer;
int timeId;
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{

    ui->setupUi(this);
    //服务器 ip port
    ui->ip->setText("0.0.0.0");
    ui->port->setText("8000");
    //初始化
    client=new QTcpSocket(this);
    checked=false;
    checked_circle=false;
    //监听
    //server->listen(QHostAddress(ui->ip->text()),ui->port->text().toInt());

    //新的链接
//    connect(server,&QTcpServer::newConnection,this,[=]()
//    {
//        //接收客户端的套接字对象 accept
//        //socket_addr 结构体 ==类 QTcpSocket
//        conn=server->nextPendingConnection();
//        QMessageBox::information(this,tr("提示"),tr("有新的链接......"),QMessageBox::Ok);
//        //保证conn是一个有效的对象，即服务器与客户端链接
//        connect(conn,&QTcpSocket::readyRead,this,[=]()
//        {
//            //接收信息
//            QByteArray contents=conn->readAll();
//            qDebug()<<"Client: "+contents;
//        });
//    });

    //接收信息
//    while(1)
//{
    connect(client,&QTcpSocket::readyRead,this,[=]()
    {
        QByteArray contents=client->readAll();
        static QByteArray buf;
        if(!contents.isEmpty()){
                buf.append(contents);
                if(contents.contains("\r\n\r\n"))
                {

                    QString ack=buf.split('\r').at(0);
                    QStringList ack_head=ack.split(' ');
                    if(ack_head.at(0)=="USRPCONNECT"){
                        if(ack_head.at(1)=="200"){
                            QMessageBox::information(this,tr("提示"),tr("USRP连接请求成功！"),QMessageBox::Ok);
                        }
                        else if(ack_head.at(1)=="401"){
                            QMessageBox::warning(this,tr("警告"),tr("USRP配置出错！"),QMessageBox::Ok);
                        }
                    }
                    else if(ack_head.at(0)=="SINGLEREQ"){
                        if(ack_head.at(1)=="200"){
                            QMessageBox::information(this,tr("提示"),tr("SINGLEREQ请求成功！"),QMessageBox::Ok);
                            const QByteArray singlereq=buf.remove(0,17);
                            QJsonDocument doc=QJsonDocument::fromJson(singlereq);
                            QJsonObject singlereq_json;
                            singlereq_json = doc.object();
                            if(!doc.isNull()){
                                    QJsonObject singlereq_json;
                                    singlereq_json = doc.object();

                                    double noise=singlereq_json.value("NOISE").toDouble();
                                    double signal=singlereq_json.value("SIGNAL").toDouble();
                                    double snr=singlereq_json.value("SNR").toDouble();
                                    double bler=singlereq_json.value("BLER").toDouble();
                                    double ber=singlereq_json.value("BER").toDouble();
                                    QString NOISE=QString::number(noise, 'e', 2);
                                    QString SIGNAL=QString::number(signal, 'e', 2);
                                    QString SNR=QString::number(snr, 'f', 2);
                                    QString BLER=QString::number(bler, 'f', 2);
                                    QString BER=QString::number(ber, 'f', 2);

                                    ui->noise->clear();
                                    ui->noise->setText(NOISE);
                                    ui->signal->clear();
                                    ui->signal->setText(SIGNAL);
                                    ui->snr->clear();
                                    ui->snr->setText(SNR);
                                    ui->bler->clear();
                                    ui->bler->setText(BLER);
                                    ui->ber->clear();
                                    ui->ber->setText(BER);
                                    QByteArray img=singlereq_json.value("PICTURE").toVariant().toByteArray();
                                    if(img.toStdString() == "{}"){
                                        ui->pic->clear();
                                    }else{
                                        QByteArray img1=QByteArray::fromBase64(img);
                                        QImage pic;
                                        pic.loadFromData(img1);
                                        pic=pic.scaled(ui->pic->size());
                                        ui->pic->clear();
                                        ui->pic->setPixmap(QPixmap::fromImage(pic));
                                    }
                                }
                        }
                        else {
                            QMessageBox::information(this,tr("提示"),tr("数据包丢失，请再次点击！"),QMessageBox::Ok);
                        }
                    }

                //
                    else if(ack_head.at(0)=="CONTINUOUSREQ")//CIRCLEREQ
                    {
                        if(ack_head.at(1)=="200"){
                            //QMessageBox::information(this,tr("提示"),tr("CIRCLEREQ请求成功！"),QMessageBox::Ok);
                            const QByteArray circlereq=buf.remove(0,17);
                            QJsonDocument doc=QJsonDocument::fromJson(circlereq);
                            QJsonObject circlereq_json;
                            circlereq_json = doc.object();

                            if(!doc.isNull()){
                                    QJsonObject circlereq_json;
                                    circlereq_json = doc.object();

                                    double noise=circlereq_json.value("NOISE").toDouble();
                                    double signal=circlereq_json.value("SIGNAL").toDouble();
                                    double snr=circlereq_json.value("SNR").toDouble();
                                    double bler=circlereq_json.value("BLER").toDouble();
                                    double ber=circlereq_json.value("BER").toDouble();
                                    vber.append(ber);
                                    vsnr.append(snr);
                                    vbler.append(vbler);
                                    qDebug("%d : ",vber.count());
                                    qDebug("ber:%.2f",ber);
                                    qDebug("bler: %.2f",bler);
                                    qDebug("snr: %.2f",snr);
                                    /*ber*/
                                    if(vber.count()==101)
                                    {
                                        QChart* chart = new QChart();
                                        QLineSeries *series = new QLineSeries();
                                        for (quint32 i = 0; i < 101; i++) {
                                            series->append(i, qLn(vber[i]));
                                        }
                                        chart->addSeries(series);
                                        chart->legend()->hide();
                                        QValueAxis *axisX = new QValueAxis ();
                                        axisX->setRange(0,100);
                                        axisX->setTitleText("Number of Packet");
                                        axisX->setLabelsVisible(true);
                                        axisX->setLabelsAngle(45);
                                        axisX->setLabelsColor(Qt::black);
                                        QFont font=axisX->labelsFont();
                                        font.setBold(true);
                                        font.setPointSize(6);
                                        axisX->setLabelsFont(font);
                                        QValueAxis *axisY = new  QValueAxis();
                                        axisY->setTitleText("SNR");
                                        axisY->setLabelsVisible(true);
                                        axisY->setLabelsAngle(0);
                                        axisY->setLabelsColor(Qt::black);
                                        QFont font10 = axisY->labelsFont();
                                        font10.setBold(true);
                                        font10.setPointSize(6);
                                        axisY->setLabelsFont(font10);
                                        chart->setAxisX(axisX,series);
                                        chart->setAxisY(axisY,series);
                                        /*ber*/
                                        /*bler*/
                                        if(vbler.count()==101)
                                        {
                                            QChart* chart2 = new QChart();
                                            QLineSeries *series2 = new QLineSeries();
                                            for (quint32 i = 0; i < 101; i++) {
                                                series2->append(i, qLn(vbler[i]));
                                            }
                                            chart2->addSeries(series2);
                                            chart2->legend()->hide();
                                            QValueAxis *axisX2 = new QValueAxis ();
                                            axisX2->setRange(0,100);
                                            axisX2->setTitleText("Number of Packet");
                                            axisX2->setLabelsVisible(true);
                                            axisX2->setLabelsAngle(45);
                                            axisX2->setLabelsColor(Qt::black);
                                            QFont font2=axisX2->labelsFont();
                                            font2.setBold(true);
                                            font2.setPointSize(6);
                                            axisX2->setLabelsFont(font2);
                                            QValueAxis *axisY2 = new  QValueAxis();
                                            axisY2->setTitleText("SNR");
                                            axisY2->setLabelsVisible(true);
                                            axisY2->setLabelsAngle(0);
                                            axisY2->setLabelsColor(Qt::black);
                                            QFont font20 = axisY2->labelsFont();
                                            font20.setBold(true);
                                            font20.setPointSize(6);
                                            axisY2->setLabelsFont(font20);
                                            chart2->setAxisX(axisX2,series2);
                                            chart2->setAxisY(axisY2,series2);
                                            /*bler*/


                                            /*snr*/
                                            if(vsnr.count()==101)
                                            {
                                                QChart* chart3 = new QChart();
                                                QLineSeries *series3 = new QLineSeries();
                                                for (quint32 i = 0; i < 101; i++) {
                                                    series3->append(i, qLn(vsnr[i]));
                                                }
                                                chart3->addSeries(series3);
                                                chart3->legend()->hide();
                                                QValueAxis *axisX3 = new QValueAxis ();
                                                axisX3->setRange(0,100);
                                                axisX3->setTitleText("Number of Packet");
                                                axisX3->setLabelsVisible(true);
                                                axisX3->setLabelsAngle(45);
                                                axisX3->setLabelsColor(Qt::black);
                                                QFont font3=axisX3->labelsFont();
                                                font3.setBold(true);
                                                font3.setPointSize(6);
                                                axisX3->setLabelsFont(font3);
                                                QValueAxis *axisY3 = new  QValueAxis();
                                                axisY3->setTitleText("SNR");
                                                axisY3->setLabelsVisible(true);
                                                axisY3->setLabelsAngle(0);
                                                axisY3->setLabelsColor(Qt::black);
                                                QFont font30 = axisY3->labelsFont();
                                                font30.setBold(true);
                                                font30.setPointSize(6);
                                                axisY3->setLabelsFont(font30);
                                                chart3->setAxisX(axisX3,series3);
                                                chart3->setAxisY(axisY3,series3);
                                                /*snr*/
                                        /*huatu*/
                                        ui->huatu->setChart(chart);                                                                                
                                        vber.clear();
                                    }





                                }
                        }
                        else {
                            QMessageBox::information(this,tr("提示"),tr("数据包丢失，请再次点击！"),QMessageBox::Ok);
                        }
                    }
                }
                else{

                    contents.clear();
                }
                buf.clear();
        }


    });
//}


}

Widget::~Widget()
{
    delete ui;
}

//发送USRP配置
void Widget::on_USRP_clicked()
{
    QStringList USRP_DATA;
    USRP_DATA<<ui->frequency->currentText().toUtf8().data();
    USRP_DATA<<ui->MODE->currentText().toUtf8().data();
    USRP_DATA<<ui->TX->currentText().toUtf8().data();
    USRP_DATA<<ui->RX->currentText().toUtf8().data();
    USRP_DATA[0]=USRP_DATA[0].split(" ").at(0);
    USRP_DATA[1]=USRP_DATA[1].split(" ").at(0);
    USRP_DATA[2]=USRP_DATA[2].split(" ").at(0);
    USRP_DATA[3]=USRP_DATA[3].split(" ").at(0);

    USRP_DATA.append("frequence");USRP_DATA.append("MODE");USRP_DATA.append("TX Gain");USRP_DATA.append("RX Gain");
    QJsonObject USRP_JSON;
    for(int i=0;i<4;i++)
    {
        USRP_JSON.insert(USRP_DATA.at(i+4),USRP_DATA.at(i));
    }

    QJsonDocument doc;
    doc.setObject(USRP_JSON);
    QByteArray data=doc.toJson(QJsonDocument::Compact);
    QString strJson(data);
    client->write("USRPCONNECT\r\n\r\n");
    client->write(strJson.toUtf8().data());


}
//连接服务器
void Widget::on_link_clicked()
{
    if(checked==false)
    {
        if(ui->ip->text().isEmpty()||ui->port->text().isEmpty())
        {
            QMessageBox::warning(this,"警告","请输入IP地址和端口号！",QMessageBox::Ok);
        }
        else
        {
            checked=true;
            if(!ip.contains(ui->ip->text())){
                ip.append(ui->ip->text().append('\n'));
            }
            if(!port.contains(ui->port->text())){
                port.append(ui->port->text().append('\n'));
            }
            ui->ip->setToolTip(ip);
            ui->port->setToolTip(port);
            client->connectToHost(QHostAddress(ui->ip->text()),ui->port->text().toInt());
            ui->link->setIcon(QIcon(":/w/qt/connect.png"));
        }

    }
    else
    {
        checked=false;
        ui->link->setIcon(QIcon(":/w/qt/disconnect.png"));
        client->disconnectFromHost();
        ui->ip->setText("0.0.0.0");
        ui->port->setText("8000");
    }
}

void Widget::on_SingleReq_clicked()
{
    QStringList SINGLEREQ_DATA;
    client->write("SINGLEREQ\r\n\r\n");
}

void Widget::on_CircleReq_clicked()
{
    if(checked_circle==false)
    {
        checked_circle=true;
        client->write("CONTINUOUSREQ\r\n\r\n");
    }
    else
    {
        checked_circle=false;
        client->disconnectFromHost();
        QMessageBox::information(this,tr("提示"),tr("finish！"),QMessageBox::Ok);
    }
}
